package com.atguigu.gulimall.ware.listener;

import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author houChen
 * @date 2022/3/1 21:52
 * @Description:
 */
@Service
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {

    @Autowired
    WareSkuService wareSkuService;

    /**
     * @Description:  (被动补偿)
     * @param null
     * @author  houChen
     * @date  2022/3/6 11:26
     */
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
        System.out.println("收到解锁库存消息...");
        try {
            wareSkuService.unlockStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            //第二个参数：true  队列来的消息被拒绝接受后，重新放到队列中，让别得消费者继续消费解锁
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
        }
    }

    /**
     * @Description:  当订单取消后解锁库存 (主动解锁库存)
     * @param null
     * @author  houChen
     * @date  2022/3/6 10:35
     */
    @RabbitHandler
    public void handleOrderCloseReleaseStock(OrderTo to, Message message, Channel channel) throws IOException {
        System.out.println("收到订单关闭消息...");
        try {
            wareSkuService.unlockStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            //第二个参数：true  队列来的消息被拒绝接受后，重新放到队列中，让别得消费者继续消费解锁
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
}